#include <cstdio>
#include <cmath>
#include <bitmap_image.hpp>

unsigned int Height, Width;

const float Rust_core[9] = {1.0, 2.0, 1.0, 2.0, 0.0, 2.0, 1.0, 2.0, 1.0};

const int Directionx[9] = {-1, -1, -1,  0, 0, 0,  1, 1, 1},
		  Directiony[9] = {-1,  0,  1, -1, 0, 1, -1, 0, 1};

bool get_Black_fix(unsigned int i, unsigned int j, unsigned int k) {
	if((signed int)i + Directionx[k] < 0 || i + Directionx[k] >= Height ||
	   (signed int)j + Directiony[k] < 0 || j + Directiony[k] >= Width) return false;
	return true;
}

unsigned char RGB_to_Black(rgb_t color) {
	return round((color.red + color.green + color.blue) / 3.0);
}

rgb_t Black_to_RGB_fix(float black) {
	black = abs(black);
	if(black > 255) black = 255;
	if(black < 0) black = 0;
	rgb_t res;
	res.red = res.green = res.blue = round(black);
	return res;
}

int main() {
	bitmap_image Input("Verticle_fix.bmp");
	
	if(!Input) {
       printf("Error - Failed to open: input.bmp\n");
       return 1;
    }
	// printf("Image read successfully!\n");
	
	// printf("Image size: %d * %d\n", Height = Input.height(), Width = Input.width());
	Height = Input.height();
	Width = Input.width();
	
	float Rust_res, Rust_nei;
	unsigned int i, j, k;//i -> row, j -> column
	for(i = 0; i < Height; i++)
		for(j = 0; j < Width; j++) {
			Rust_res = 0;
			for(k = 0; k < 9; k++) {
				if(!get_Black_fix(i, j, k)) continue;
				Rust_nei = RGB_to_Black(Input.get_pixel(j + Directiony[k], i + Directionx[k])) * Rust_core[k] * 2;
				if(Rust_nei > 255) Rust_nei = 255;
				Rust_res += Rust_nei;
			}
			if(Rust_res <= 900.0) Input.set_pixel(j, i, Black_to_RGB_fix(0));
		}
	// printf("Convolution run successfully!\n");
	Input.save_image("RustOutput.bmp");
	return 0;
}
